<?php
/**
 * Created by PhpStorm.
 * 店铺业务处理
 * User: caicm
 * Date: 2017/6/15
 * Time: 19:52
 */

namespace WMApi\Service;

use WMApi\Model\RegionModel;
use WMApi\Model\WmStoreActionModel;
use WMApi\Model\WmStoreClassifyModel;
use WMApi\Model\WmStoreModel;

class SellerStoreService {

    /**
     * 店铺申请业务
     * Created By caicm
     * @param int $seller_id 商家id
     * @param string $store_name 店铺名称
     * @param string $store_introduce 店铺描述
     * @param int $classify_id 店铺运营分类id（二级）
     * @param string $province 省份
     * @param string $city 城市
     * @param string $district 区
     * @param string $address 地址详情
     * @param string $sign_building 地标
     * @param string $address_name  门牌号
     * @param string $contacts 联系人
     * @param int $contacts_phone 联系人电话
     * @param string $start_time 店铺运营开始时间
     * @param string $end_time 店铺运营结束时间
     * @param int $starting_money 起送金额
     * @param int $store_sw 店铺开关（1：营业，2：休息）
     * @param string $store_img 店铺图片
     * @param int $shipping_fee 配送费用
     * @param int $shipping_way 配送方式 1-周边配 2-干线全城配
     * @param int $shipping_radius 配送半径（公里）
     * @return mixed
     */
    public function apply_store($seller_id=0, $store_name='', $store_introduce='', $classify_id=0, $province='', $city='', $district='', $address='', $sign_building='', $address_name='', $contacts='', $contacts_phone=0, $start_time='', $end_time='', $starting_money=0, $store_sw=0, $store_img='', $shipping_fee=0, $shipping_way=0, $shipping_radius=0){

        $classify_model = new WmStoreClassifyModel();
        $store_model = new WmStoreModel();

        $this->check_shipping_radius($shipping_way, $shipping_radius);

        //处理地址
        $address_data = $this->dispose_address($province, $city, $district, $address);

        //运营时间转换
        $start_time = str_replace(':', '', $start_time);
        $end_time = str_replace(':', '', $end_time);

        //获取运营分类（一级分类id）
        $parent_classify_id = $classify_model->find_parent_classify_id($classify_id);
        if(!$parent_classify_id){
            returnApiError('不能选择一级分类');
        }

        //获取商家店铺数量
        $store_num = $store_model->find_store_num($seller_id);
        //是否默认店铺（商家没有店铺的时候设为默认店铺）
        $is_default = $store_num ? 0 : 1;
        if($store_num >= C('max_store_num')){
            returnApiError('最多只能申请'.C('max_store_num').'个店铺');
        }

        $store_model->startTrans();
        $store_action_model = new WmStoreActionModel();

        /**
         * 添加物流取货点
         */
        /*$bsc_service = new BscService();
        $state = $bsc_service->add_scc($address_data['longitude'], $address_data['latitude'], $store_name, $address_data['province_name'], $address_data['city_name'], $address_data['district_name'], $address_data['address'], $shipping_radius, '');
        if($state['status'] != 1){
            returnApiError('写入物流取货点失败');
        }

        $scc_id = $state['id']; //取货点id*/

        $scc_id = 0;

        /**
         * 写入店铺表
         */
        $add_store = $store_model->add_store($seller_id, $store_name, $store_introduce, $classify_id, $parent_classify_id, $address_data, $sign_building, $address_name, $contacts, $contacts_phone, $start_time, $end_time, $starting_money, $store_sw, $is_default, $store_img, $shipping_fee, $shipping_way, $shipping_radius, $scc_id);

        /**
         * 写入店铺操作记录
         */
        $remark = '新增店铺';
        $add_action = $store_action_model->add_action($seller_id, $add_store, $store_sw, 2, 2, $remark);

        if($add_store && $add_action){
            $store_model->commit();
            return $add_store;
        }else{
            $store_model->rollback();
            return false;
        }
    }

    /**
     * 编辑店铺
     * Created By caicm
     * @param int $seller_id 商家id
     * @param int $store_id 店铺id
     * @param string $store_name 店铺名称
     * @param string $store_introduce 店铺描述
     * @param int $classify_id 店铺运营分类id（二级）
     * @param string $province 省份
     * @param string $city 城市
     * @param string $district 区
     * @param string $address 地址详情
     * @param string $sign_building 地标
     * @param string $address_name  门牌号
     * @param string $contacts 联系人
     * @param int $contacts_phone 联系人电话
     * @param string $start_time 店铺运营开始时间
     * @param string $end_time 店铺运营结束时间
     * @param int $starting_money 起送金额
     * @param int $store_sw 店铺开关（1：营业，2：休息）
     * @param string $store_img 店铺图片
     * @param int $shipping_fee 配送费用
     * @param int $shipping_way 配送方式 1-周边配 2-干线全城配
     * @param int $shipping_radius 配送半径（公里）
     * @param int $is_default  是否默认店铺 0-否 1-是
     * @return bool
     */
    public function edit_store($seller_id=0, $store_id=0, $store_name='', $store_introduce='', $classify_id=0, $province='', $city='', $district='', $address='', $sign_building='', $address_name='', $contacts='', $contacts_phone=0, $start_time='', $end_time='', $starting_money=0, $store_sw=0, $store_img='', $shipping_fee=0, $shipping_way=0, $shipping_radius=0, $is_default=0){

        $store_model = new WmStoreModel();
        $classify_model = new WmStoreClassifyModel();
        $store_model->startTrans();
        $edit_all_store = true;

        $this->check_shipping_radius($shipping_way, $shipping_radius);

        $store_info = $store_model->find_store_info($seller_id, $store_id);
        if(!$store_info){
            returnApiError('店铺不存在');
        }

        if($store_info['store_audit'] == 2){
            returnApiError('店铺正在审核中，不能修改');
        }

        //处理地址
        $address_data = $this->dispose_address($province, $city, $district, $address);

        //运营时间转换
        $start_time = str_replace(':', '', $start_time);
        $end_time = str_replace(':', '', $end_time);

        //获取运营分类（一级分类id）
        $parent_classify_id = $classify_model->find_parent_classify_id($classify_id);
        if(!$parent_classify_id){
            returnApiError('不能选择一级分类');
        }

        /**
         * 当前商家所有店铺状态改为0
         */
        if($is_default==1 && $store_info['is_default']==0){
            $edit_all_store = $store_model->edit_store_is_default($seller_id);
        }

        /**
         * 编辑店铺
         */
        $edit_store = $store_model->edit_store($seller_id, $store_id, $store_name, $store_introduce, $classify_id, $parent_classify_id, $address_data, $sign_building, $address_name, $contacts, $contacts_phone, $start_time, $end_time, $starting_money, $store_sw, $store_img, $shipping_fee, $shipping_way, $shipping_radius, $is_default, $store_info['store_audit']);

        if($edit_all_store && $edit_store){
            $store_model->commit();
            return true;
        }else{
            $store_model->rollback();
            return false;
        }
    }

    /**
     * 检查配送半径、配送方式
     * Created By caicm
     * @param int $shipping_way
     * @param int $shipping_radius
     * @return bool
     */
    protected function check_shipping_radius($shipping_way=0, $shipping_radius=0){
        $data = get_shipping_way();

        if(!$data[$shipping_way]){
            returnApiError('配送方式有误');
        }
        if($data[$shipping_way]['is_shipping_radius']){
            if(empty($shipping_radius) || !in_array($shipping_radius, get_shipping_radius())){
                returnApiError('配送半径');
            }
        }
        return true;
    }


    /**
     * 处理地址
     * Created By caicm
     * @param string $province
     * @param string $city
     * @param string $district
     * @param string $address
     * @return array
     */
    public function dispose_address($province='', $city='', $district='', $address=''){
        $region = new RegionModel();


        //地址详情（去掉省市区）
        $address = str_replace(array($province,$city,$district), array('','',''), $address);

        //地址处理（省、市、区）
        $province_info = $region->get_address($province, 1);
        $city_info = $region->get_address($city, 2);
        $district_ifo = $region->get_address($district, 3);

        //根据地址获取坐标
        $lnglat = get_lng_lat ( $province . $city . $district . $address );
        if ($lnglat) {
            $longitude = $lnglat ['lng'];
            $latitude = $lnglat ['lat'];
        } else {
            $longitude = '';
            $latitude = '';
        }

        $province = $province_info['region_id'];
        $province_name = $province_info['region_name'];
        $city = $city_info['region_id'];
        $city_name = $city_info['region_name'];
        $district = $district_ifo['region_id'];
        $district_name = $district_ifo['region_name'];

        return array(
            'province' => $province,
            'city' => $city,
            'district' => $district,
            'province_name' => $province_name,
            'city_name' => $city_name,
            'district_name' => $district_name,
            'address' => $address,
            'longitude' => $longitude,
            'latitude' => $latitude
        );

    }

    /**
     * 获取商家店铺列表
     * Created By caicm
     * @param int $seller_id
     * @return mixed
     */
    public function get_store_list($seller_id=0){
        $shipping_way_list = get_shipping_way();
        $store_model = new WmStoreModel();
        $store_list = $store_model->find_store_list($seller_id);
        foreach ($store_list as $key=>$val){
            $store_list[$key]['store_state'] = $this->get_store_state($val['store_audit'], $val['store_sw']);
            $store_list[$key]['add_time'] = local_date('Y-m-d', $val['add_time']);
            $store_list[$key]['start_time'] = get_str_to_time($val['start_time']);
            $store_list[$key]['end_time'] = get_str_to_time($val['end_time']);
            $store_list[$key]['shipping_way_id'] = $shipping_way_list[$val['shipping_way']]['shipping_way_id'];
            $store_list[$key]['shipping_way_name'] = $shipping_way_list[$val['shipping_way']]['shipping_way_name'];
            unset($store_list[$key]['store_audit']);
            unset($store_list[$key]['store_sw']);
            unset($store_list[$key]['shipping_way']);
        }
        return $store_list;
    }

    /**
     * 获取店铺状态
     * Created By caicm
     * @param int $store_audit
     * @param int $store_sw
     * @return string
     */
    protected function get_store_state($store_audit=0, $store_sw=0){
        if($store_audit == 1){
            $store_state = ($store_sw==1 ? '运营中' : '休息中');
        }elseif($store_audit == 2){
            $store_state = '审核中';
        }elseif($store_audit == 3){
            $store_state = '审核不通过';
        }
        return $store_state;
    }

    /**
     * 设置店铺为当前店铺
     * Created By caicm
     * @param $seller_id
     * @param $store_id
     * @return bool
     */
    public function edit_store_is_default($seller_id, $store_id){
        $store_model = new WmStoreModel();
        $store_model->startTrans();

        /**
         * 当前商家所有店铺状态改为0
         */
        $edit_all_store = $store_model->edit_store_is_default($seller_id);

        /**
         * 修改当前店铺为默认状态
         */
        $edit_store = $store_model->edit_store_is_default($seller_id, $store_id, 1);

        if($edit_all_store && $edit_store){
            $store_model->commit();
            return true;
        }else{
            $store_model->rollback();
            return false;
        }
    }

    /**
     * 获取默认店铺信息
     * Created By caicm
     * @param int $seller_id
     * @return mixed
     */
    public function get_default_store($seller_id=0){
        $store_model = new WmStoreModel();
        $store_info = $store_model->find_default_store($seller_id);
        if(!$store_info){
            returnApiError('还没创建店铺，请先创建店铺');
        }
        $store_info['store_state'] = $this->get_store_state($store_info['store_audit'], $store_info['store_sw']);
        $store_info['add_time'] = local_date('Y-m-d', $store_info['add_time']);
        $store_info['start_time'] = get_str_to_time($store_info['start_time']);
        $store_info['end_time'] = get_str_to_time($store_info['end_time']);
        return $store_info;
    }
}